package com.cakeclient;


import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TabHost;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.actionbarsherlock.view.Window;
import com.cakeclient.Model.Client;
import com.cakeclient.Model.Parameters;
import com.cakeclient.facebookmodel.BaseRequestListener;
import com.cakeclient.facebookmodel.SessionStore;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import org.json.JSONException;
import org.json.JSONObject;


public class MainParametersActivity extends SherlockFragmentActivity {
    public static final String APP_ID = "368227953233723";
    public Facebook mFacebook;
    private AsyncFacebookRunner mAsyncRunner;

    TabHost mTabHost;
    MainActivity.TabManager mTabManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //setTheme(com.actionbarsherlock.sample.fragments.R.style.Theme_Sherlock_Light);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen_layout);



        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup();

        mTabManager = new MainActivity.TabManager(this, mTabHost, R.id.realtabcontent);

        mTabManager.addTab(mTabHost.newTabSpec("Accounts").setIndicator("accounts"),
                ClientManageAccountsFragment.class, null);
        mTabManager.addTab(mTabHost.newTabSpec("Parameters").setIndicator("parameter"),
                ClientParameterFragment.class, null);
        mTabManager.addTab(mTabHost.newTabSpec("Feedback").setIndicator("feedBack"),
                ClientFeedBackFragment.class, null);


        if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
        }

        setSupportProgressBarIndeterminateVisibility(false);

        (new SyncTaskManager.storeUpdate(getBaseContext())).execute(0);

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);    //To change body of overridden methods use File | Settings | File Templates.

        mFacebook = new Facebook(APP_ID);
        mAsyncRunner = new AsyncFacebookRunner(mFacebook);

        SessionStore.restore(mFacebook, this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("tab", mTabHost.getCurrentTabTag());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mFacebook.authorizeCallback(requestCode, resultCode, data);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        SubMenu subMenu1 = menu.addSubMenu("BACK");

        MenuItem subMenu1Item = subMenu1.getItem().setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                finish();
                return false;  //To change body of implemented methods use File | Settings | File Templates.
            }
        });
        subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        return super.onCreateOptionsMenu(menu);
    }



    //--------------------- Fonction fb

    //Demande d'actualisation
    public void updateInformations(){
        mAsyncRunner.request("me", new SampleRequestListener());
    }

    //Requete du nom
    public class SampleRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            try {
                // process the response here: executed in background thread
                Log.d("Facebook-Example", "Response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                final String name = json.getString("name");
                final String id  = json.getString("id");

                // then post the processed result back to the UI thread
                // if we do not do this, an runtime exception will be generated
                // e.g. "CalledFromWrongThreadException: Only the original
                // thread that created a view hierarchy can touch its views."
                MainParametersActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        // Sauvegarde de l'ID (pour récup l'image)
                        Parameters.setFacebookId(getApplicationContext(),id);

                        // Sauvegarde du nom
                        Parameters.setFacebookName(getApplicationContext(),name);

                    }
                });
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
        }
    }




    // -------------------Fin fonction fb
    public void LaunchRegisterFragment(View view) {

        (new LaunchRegisterFragment()).execute();
    }

    public void LaunchRegister2Fragment(Client client) {

        (new LaunchRegister2Fragment(client)).execute();
    }

    public void LaunchAccountsFragment() {

        (new LaunchAccountsFragment()).execute();
    }




    private class LaunchRegisterFragment extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();    //To change body of overridden methods use File | Settings | File Templates.
            setSupportProgressBarIndeterminateVisibility(true);

        }

        @Override
        protected String doInBackground(String... strings) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    mTabManager.loadNewFragment(new ClientRegisterFragment());


                }
            }).start();
            return null;  //To change body of implemented methods use File | Settings | File Templates.
        }
        @Override
        protected void onPostExecute(String result) {
            setSupportProgressBarIndeterminateVisibility(false);

        }
    }

    private class LaunchRegister2Fragment extends AsyncTask<String, Void, String> {
        private Client client;
        public LaunchRegister2Fragment(Client client){
            this.client = client;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();    //To change body of overridden methods use File | Settings | File Templates.
            setSupportProgressBarIndeterminateVisibility(true);

        }

        @Override
        protected String doInBackground(String... strings) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    mTabManager.loadNewFragment(new ClientRegisterFragment2(client));


                }
            }).start();
            return null;  //To change body of implemented methods use File | Settings | File Templates.
        }
        @Override
        protected void onPostExecute(String result) {
            setSupportProgressBarIndeterminateVisibility(false);

        }
    }

    private class LaunchAccountsFragment extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();    //To change body of overridden methods use File | Settings | File Templates.
            setSupportProgressBarIndeterminateVisibility(true);

        }

        @Override
        protected String doInBackground(String... strings) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    mTabManager.loadNewFragment(new ClientManageAccountsFragment());


                }
            }).start();
            return null;  //To change body of implemented methods use File | Settings | File Templates.
        }
        @Override
        protected void onPostExecute(String result) {
            setSupportProgressBarIndeterminateVisibility(false);

        }



    }





}
